﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Think9.Models;
using Think9.Services.Base;
using Think9.Services.Basic;
using Think9.Services.Table;

namespace Think9.Controllers.Basic
{
    [Area("SysTable")]
    public class TbSetUpController : BaseController
    {
        private TbIndexService TbIndexService = new TbIndexService();
        private ComService ComService = new ComService();
        private SortService SortService = new SortService();
        private TbBasicService TbBasicService = new TbBasicService();
        private IndexDateType IndexDtaeTypeService = new IndexDateType();

        //
        public ActionResult TbIndexList(string tbid)
        {
            ViewBag.tbid = tbid;
            return View();
        }

        //
        public ActionResult ColumnList(string tbid)
        {
            ViewBag.tbid = tbid;
            return View();
        }

        //
        public ActionResult SelectRuleList(string tbid, string indexid, string ismuch)
        {
            ViewBag.ismuch = ismuch;

            String show = "";
            String datatype = "";
            IndexBasicService IndexBasicService = new IndexBasicService();

            if (string.IsNullOrEmpty(tbid) && string.IsNullOrEmpty(indexid))
            {
                var modelTb = TbBasicService.GetByWhereFirst("where TbId=@TbId", new { TbId = tbid });

                string sTBName = modelTb == null ? "" : modelTb.TbName;
                if (sTBName.Length > 20)
                {
                    sTBName = sTBName.Substring(0, 20) + ".. ";
                }

                var modelIndex = IndexBasicService.GetByWhereFirst("where indexid=@indexid", new { indexid = indexid });
                string IndexName = modelIndex == null ? "" : modelIndex.IndexName;
                datatype = modelIndex == null ? "" : modelIndex.IndexDataType;

                show = sTBName + "" + IndexName + "--选择数据规范";
            }

            ViewBag.tbid = tbid;
            ViewBag.indexid = indexid;
            ViewBag.show = show;
            ViewBag.datatype = datatype;

            return View();
        }

        public ActionResult UpIndex1(string tbid, string indexid)
        {
            ViewBag.tbid = tbid;
            ViewBag.ControlType = new SelectList(ControlType.GetMainTbControlType(), "Value", "Text");
            ViewBag.ValidateList = new SelectList(ValidateList.GetValidateList(), "Value", "Text");

            string where = "where TbId=@TbId and indexid=@indexid ";
            object param = new { TbId = tbid, indexid = indexid };

            TbIndexEntity model = TbIndexService.GetByWhereFirst(where, param);
            if (model != null)
            {
                foreach (IndexDtaeTypeEntity obj in IndexDtaeTypeService.GetIndexDtaeType())
                {
                    if (model.DataType == obj.TypeId)
                    {
                        model.DataType = obj.TypeName;
                        break;
                    }
                }

                model.BShow = model.BShow == null ? "1" : model.BShow;

                RuleListService rulelist = new RuleListService();
                model.RuleName = rulelist.GetRuleNameByID(model.RuleId, model.BSelMuch);
                return View(model);
            }
            else
            {
                return Json("数据不存在！");
            }
        }

        public ActionResult Column(string tbid, string indexid)
        {
            ViewBag.tbid = tbid;
            ViewBag.ControlType = new SelectList(ControlType.GetGridTbControlType(), "Value", "Text");
            ViewBag.ValidateList = new SelectList(ValidateList.GetValidateList(), "Value", "Text");

            string where = "where TbId=@TbId and indexid=@indexid ";
            object param = new { TbId = tbid, indexid = indexid };

            TbIndexEntity model = TbIndexService.GetByWhereFirst(where, param);
            if (model != null)
            {
                foreach (IndexDtaeTypeEntity obj in IndexDtaeTypeService.GetIndexDtaeType())
                {
                    if (model.DataType == obj.TypeId)
                    {
                        model.DataType = obj.TypeName;
                        break;
                    }
                }

                RuleListService rulelist = new RuleListService();
                model.RuleName = rulelist.GetRuleNameByID(model.RuleId, model.BSelMuch);
                return View(model);
            }
            else
            {
                return Json("数据不存在！");
            }
        }

        public ActionResult UpIndex2(string tbid)
        {
            ViewBag.TbSortList = new SelectList(SortService.GetAll("ClassID,SortID,SortName", "ORDER BY SortOrder").Where(x => x.ClassID == "CAT_table"), "SortID", "SortName");
            ViewBag.DtaeTypeList = new SelectList(IndexDtaeTypeService.GetIndexDtaeType(), "TypeId", "TypeName");
            ViewBag.IndexSortList = new SelectList(SortService.GetAll("ClassID,SortID,SortName", "ORDER BY SortOrder").Where(x => x.ClassID == "CAT_index"), "SortID", "SortName");
            ViewBag.tbid = HttpContext.Request.Query["tbid"].ToString();
            return View();
        }

        public ActionResult DBTable(string tbid)
        {
            ViewBag.tbid = tbid;
            return View();
        }

        public ActionResult GetDbFieldist(string tbid)
        {
            DataTable dt = ComService.GetTbFieldist(tbid);

            IEnumerable<TbIndexEntity> _index = TbIndexService.GetByWhere("where TbId = @TbId", new { TbId = tbid }, "IndexId,IndexName", "ORDER BY IndexOrderNo");

            List<DbFieldEntity> list = new List<DbFieldEntity>();

            foreach (DataRow dr in dt.Rows)
            {
                DbFieldEntity obj = new DbFieldEntity();
                obj.ColumnName = dr["COLUMN_NAME"].ToString();
                obj.DataType = dr["DATA_type"].ToString();
                foreach (TbIndexEntity model in _index)
                {
                    if (obj.ColumnName == model.IndexId)
                    {
                        obj.IndexName = model.IndexName;
                    }
                }
                list.Add(obj);
            }

            var result = new { code = 0, msg = "", count = dt.Rows.Count, data = list };

            return Json(result);
        }

        //打开校验页面
        [HttpGet]
        public ActionResult PUFormula(string tbid, string fid, string some)
        {
            ViewBag.tbid = tbid;
            ViewBag.formid = fid;
            ViewBag.some = some;
            return View();
        }

        [HttpPost]
        public ActionResult GetTbIndexList(TbIndexEntity model, PageInfoEntity pageInfo, string tbid)
        {
            string _tbid = tbid == null ? "" : tbid;
            if (!_tbid.StartsWith("tb_"))
            {
                _tbid = "tb_" + _tbid;
            }

            long total = 0;
            IEnumerable<dynamic> list = TbIndexService.GetTbIndexList(model, pageInfo, _tbid, ref total);

            var result = new { code = 0, msg = "", count = total, data = list };

            return Json(result);
        }

        [HttpPost]
        public ActionResult GetTbIndexList2(TbIndexEntity model, PageInfoEntity pageInfo, string tbid)
        {
            string _tbid = tbid == null ? "" : tbid;
            if (!_tbid.StartsWith("tb_"))
            {
                _tbid = "tb_" + _tbid;
            }

            long total = 0;
            IEnumerable<dynamic> list = TbIndexService.GetTbIndexList2(model, pageInfo, _tbid, ref total);

            var result = new { code = 0, msg = "", count = total, data = list };

            return Json(result);
        }

        [HttpPost]
        public ActionResult GetTbIndexList3(TbIndexEntity model, PageInfoEntity pageInfo, string tbid)
        {
            string _tbid = tbid == null ? "" : tbid;
            if (!_tbid.StartsWith("tb_"))
            {
                _tbid = "tb_" + _tbid;
            }

            long total = 0;
            IEnumerable<dynamic> list = TbIndexService.GetTbIndexList3(model, pageInfo, _tbid, ref total);

            var result = new { code = 0, msg = "", count = total, data = list };

            return Json(result);
        }

        [HttpGet]
        public ActionResult GetIndexListByTbID(string tbid, string fid)
        {
            tbid = tbid == null ? "" : tbid;
            List<valueTextEntity> list = TbIndexService.GetIndexByTbID(tbid, fid);
            var result = new { code = 0, msg = "", count = list.Count, data = list };

            return Json(result);
        }

        [HttpPost]
        public ActionResult AddTbIndexByStr(string tbid, string si)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(tbid))
                {
                    return Json(ErrorTip("操作失败tbid为空"));
                }
                else
                {
                    if (!tbid.StartsWith("tb_"))
                    {
                        tbid = "tb_" + tbid;
                    }
                    string sindex = si == null ? "" : si;
                    int icount = 0;
                    string[] arr = BaseUtil.GetStrArray(sindex, ",");// 以;分割
                    for (int i = 0; i < arr.GetLength(0); i++)
                    {
                        if (arr[i] != null)
                        {
                            string index = arr[i].ToString().Trim();
                            TbIndexService.AddTbIndex(ref icount, tbid, index);
                        }
                    }

                    string userid = CurrentUser == null ? "" : CurrentUser.Account;
                    Record.AddRecord(userid, tbid, "添加指标" + sindex);

                    return Json(SuccessTip("共添加" + icount.ToString() + "指标"));
                }
            }
            catch (Exception ex)
            {
                return Json(ErrorTip(ex.Message));
            }
        }

        [HttpPost]
        public ActionResult RemoveTbIndexByStr(string tbid, string si)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(tbid))
                {
                    return Json(ErrorTip("操作失败tbid为空"));
                }
                else
                {
                    if (!tbid.StartsWith("tb_"))
                    {
                        tbid = "tb_" + tbid;
                    }
                    string sindex = si == null ? "" : si;
                    int icount = 0;
                    string[] arr = BaseUtil.GetStrArray(sindex, ",");// 以;分割
                    for (int i = 0; i < arr.GetLength(0); i++)
                    {
                        if (arr[i] != null)
                        {
                            string index = arr[i].ToString().Trim();

                            TbIndexService.DeleteByWhere("where TbId='" + tbid + "' and IndexId='" + index + "'");

                            //删除表javascript关系
                            TbBasicService.DeletTbIndexJs(tbid, index);
                            //删除表事件
                            TbBasicService.DeletTbEvent(tbid, index);
                            //删除自动编号
                            TbBasicService.DeleteRuleAutoNoByTbIndex(tbid, index);

                            //数据库添加字段
                            if (ComService.TabExists(tbid))
                            {
                                if (ComService.ColumnExists(tbid, index))
                                {
                                    string sql = "ALTER TABLE " + tbid + "  DROP  COLUMN  " + index + "";
                                    ComService.ExecuteSql(sql);
                                }
                            }

                            icount++;
                        }
                    }

                    string userid = CurrentUser == null ? "" : CurrentUser.Account;
                    Record.AddRecord(userid, tbid, "移除指标" + sindex);

                    return Json(SuccessTip("共移除" + icount.ToString() + "指标"));
                }
            }
            catch (Exception ex)
            {
                return Json(ErrorTip(ex.Message));
            }
        }

        [HttpPost]
        public ActionResult UpTbIndexWidthAndNo(IEnumerable<TbIndexEntity> list)
        {
            var _indexid = "";
            var _tbid = "";
            var _no = "";
            var _width = "";
            string userid = CurrentUser == null ? "" : CurrentUser.Account;
            try
            {
                foreach (TbIndexEntity obj in list)
                {
                    _indexid = ((TbIndexEntity)obj).IndexId;
                    _tbid = ((TbIndexEntity)obj).TbId;
                    _no = ((TbIndexEntity)obj).IndexOrderNo.ToString();
                    _width = ((TbIndexEntity)obj).ColumnWith.ToString();

                    TbIndexService.UpdateByWhere("where IndexId='" + _indexid + "' and TbId='" + _tbid + "' ", "IndexOrderNo,ColumnWith", (TbIndexEntity)obj);
                    Record.AddRecord(userid, _tbid, "编辑指标属性" + _indexid + "[IndexOrderNo=" + _no + "][width=" + _width + "]");
                }

                var result = SuccessTip("保存成功");
                return Json(result);
            }
            catch (Exception ex)
            {
                return Json(ErrorTip(ex.Message));
            }
        }

        [HttpPost]
        public ActionResult UpTbIndexWidth(IEnumerable<TbIndexEntity> list)
        {
            var _indexid = "";
            var _tbid = "";
            var _no = "";
            var _width = "";
            string userid = CurrentUser == null ? "" : CurrentUser.Account;

            try
            {
                foreach (TbIndexEntity obj in list)
                {
                    _indexid = ((TbIndexEntity)obj).IndexId;
                    _tbid = ((TbIndexEntity)obj).TbId;
                    _no = ((TbIndexEntity)obj).IndexOrderNo.ToString();
                    _width = ((TbIndexEntity)obj).ColumnWith.ToString();

                    TbIndexService.UpdateByWhere("where IndexId='" + _indexid + "' and TbId='" + _tbid + "' ", "ColumnWith", (TbIndexEntity)obj);
                    Record.AddRecord(userid, _tbid, "编辑指标属性" + _indexid + "[width=" + _width + "]");
                }

                var result = SuccessTip("保存成功");
                return Json(result);
            }
            catch (Exception ex)
            {
                return Json(ErrorTip(ex.Message));
            }
        }

        [HttpPost]
        public ActionResult UpTbIndexSome(string tbid, string indexid, string name, bool isState)
        {
            string err = "";
            string where = "where IndexId='" + indexid + "' and TbId='" + tbid + "' ";
            TbIndexEntity model = new TbIndexEntity();

            if (name == "BEmpty")
            {
                if (isState)
                {
                    model.BEmpty = "2";
                }
                else
                {
                    model = TbIndexService.GetByWhereFirst(where);
                    if (model.BUnique == "1")
                    {
                        err += " 已设置为唯一属性，不能修改必填属性";
                    }
                    if (model.BPK == "1")
                    {
                        err += " 已设置为主键属性，不能修改必填属性";
                    }

                    model.BEmpty = "1";
                }
            }

            if (name == "BOrder")
            {
                model.BOrder = "2";
                if (isState)
                {
                    model.BOrder = "1";
                }
            }

            if (name == "BLock")
            {
                model.BLock = "2";
                if (isState)
                {
                    model.BLock = "1";
                }
            }

            if (name == "BColumnShow2")
            {
                model.BColumnShow2 = "2";
                if (isState)
                {
                    model.BColumnShow2 = "1";
                }
            }

            if (name == "BColumnShow")
            {
                model.BColumnShow = "2";
                if (isState)
                {
                    model.BColumnShow = "1";
                }
            }

            if (name == "BSearch2")
            {
                model.BSearch2 = "2";
                if (isState)
                {
                    model.BSearch2 = "1";
                }
            }

            if (name == "BSearch")
            {
                model.BSearch = "2";
                if (isState)
                {
                    model.BSearch = "1";
                }
            }

            if (name == "BShow")
            {
                model.BShow = "1";
                if (isState)
                {
                    model.BShow = "2";
                }
            }

            if (name == "BSelMuch")
            {
                model.BSelMuch = "2";
                if (isState)
                {
                    model.BSelMuch = "1";
                }
            }

            try
            {
                if (string.IsNullOrEmpty(err))
                {
                    err = TbIndexService.UpdateByWhere(where, name, model) > 0 ? "" : "保存失败";
                }

                if (string.IsNullOrEmpty(err))
                {
                    string userid = CurrentUser == null ? "" : CurrentUser.Account;
                    Record.AddRecord(userid, tbid, "编辑指标属性：" + indexid + "[" + name + "]");

                    return Json(SuccessTip("保存成功"));
                }
                else
                {
                    return Json(ErrorTip(err));
                }
            }
            catch (Exception ex)
            {
                return Json(ErrorTip(ex.Message));
            }
        }

        [HttpPost]
        public ActionResult UpTbIndexByTbIndexID(TbIndexEntity model, string tbid, string indexid)
        {
            try
            {
                string err = TbIndexService.UpMainTbIndex(model, tbid, indexid);
                if (err == "")
                {
                    string userid = CurrentUser == null ? "" : CurrentUser.Account;
                    string str = "[IndexName=" + model.IndexName + "]" + "[ListStat=" + model.ListStat + "]" + "[ListHeadName=" + model.ListHeadName + "]" + "[ColumnWith=" + model.ColumnWith + "]" + "[BPK=" + model.BPK + "]" + "[BUnique=" + model.BUnique + "]" + "[BEmpty=" + model.BEmpty + "]" + "[BColumnShow=" + model.BColumnShow + "]" + "[BColumnShow2=" + model.BColumnShow2 + "]" + "[BSearch=" + model.BSearch + "]" + "[BOrder=" + model.BOrder + "]" + "[BLock=" + model.BLock + "]" + "[BLock2=" + model.BLock2 + "]" + "[BTime=" + model.BTime + "]" + "[IndexOrderNo=" + model.IndexOrderNo + "]" + "[DefaultV=" + model.DefaultV + "]" + "[RuleName=" + model.RuleName + "]" + "[RuleType=" + model.RuleType + "]" + "[RuleId=" + model.RuleId + "]" + "[BSelMuch=" + model.BSelMuch + "]" + "[ControlType=" + model.ControlType + "]...";
                    Record.AddRecord(userid, tbid, "编辑指标属性:" + indexid + str);

                    return Json(SuccessTip("保存成功"));
                }
                else
                {
                    return Json(ErrorTip(err));
                }
            }
            catch (Exception ex)
            {
                return Json(ErrorTip(ex.Message));
            }
        }

        [HttpPost]
        public ActionResult UpGridTbIndex(TbIndexEntity model, string tbid, string indexid)
        {
            try
            {
                string err = TbIndexService.UpGridTbIndex(model, tbid, indexid);
                if (err == "")
                {
                    string userid = CurrentUser == null ? "" : CurrentUser.Account;
                    string str = "[IndexName=" + model.IndexName + "]" + "[ListStat=" + model.ListStat + "]" + "[ListHeadName=" + model.ListHeadName + "]" + "[ColumnWith=" + model.ColumnWith + "]" + "[BPK=" + model.BPK + "]" + "[BUnique=" + model.BUnique + "]" + "[BEmpty=" + model.BEmpty + "]" + "[BColumnShow=" + model.BColumnShow + "]" + "[BColumnShow2=" + model.BColumnShow2 + "]" + "[BSearch=" + model.BSearch + "]" + "[BOrder=" + model.BOrder + "]" + "[BLock=" + model.BLock + "]" + "[BLock2=" + model.BLock2 + "]" + "[BTime=" + model.BTime + "]" + "[IndexOrderNo=" + model.IndexOrderNo + "]" + "[DefaultV=" + model.DefaultV + "]" + "[RuleName=" + model.RuleName + "]" + "[RuleType=" + model.RuleType + "]" + "[RuleId=" + model.RuleId + "]" + "[BSelMuch=" + model.BSelMuch + "]" + "[ControlType=" + model.ControlType + "]...";
                    Record.AddRecord(userid, tbid, "编辑指标属性:" + indexid + str);

                    return Json(SuccessTip("保存成功"));
                }
                else
                {
                    return Json(ErrorTip(err));
                }
            }
            catch (Exception ex)
            {
                return Json(ErrorTip(ex.Message));
            }
        }

        [HttpPost]
        public ActionResult UpTbIndexRule(string ruleid, string tbid, string indexid)
        {
            string name = "";
            string err = "";

            string _ruleid = ruleid == null ? "" : ruleid;

            try
            {
                if (_ruleid.Trim() == "")
                {
                    return this.RemoveTbIndexRule(tbid, indexid);
                }
                else
                {
                    err = TbBasicService.UpTbIndexByTbIndexIDAndRuleID(ref name, _ruleid, tbid, indexid);
                }

                if (err == "")
                {
                    string userid = CurrentUser == null ? "" : CurrentUser.Account;
                    Record.AddRecord(userid, tbid, "编辑指标数据规范:" + indexid + "[" + _ruleid + "]");

                    return Json(SuccessTip("保存成功", name));
                }
                else
                {
                    return Json(ErrorTip(err));
                }
            }
            catch (Exception ex)
            {
                return Json(ErrorTip(ex.ToString()));
            }
        }

        [HttpPost]
        public ActionResult RemoveTbIndexRule(string tbid, string indexid)
        {
            try
            {
                string Err = TbBasicService.RemoveTbIndexRule(tbid, indexid);

                if (Err == "")
                {
                    return Json(SuccessTip("保存成功", ""));
                }
                else
                {
                    return Json(ErrorTip(Err));
                }
            }
            catch (Exception ex)
            {
                return Json(ErrorTip(ex.Message));
            }
        }

        [HttpPost]
        public ActionResult UpTbIndexControlType(string typeid, string tbid, string indexid)
        {
            try
            {
                string err = TbBasicService.UpTbIndexControlType(typeid, tbid, indexid);

                if (err == "")
                {
                    string userid = CurrentUser == null ? "" : CurrentUser.Account;
                    Record.AddRecord(userid, tbid, "编辑指标控件类型:" + indexid + "[" + typeid + "]");

                    return Json(SuccessTip("保存成功"));
                }
                else
                {
                    return Json(ErrorTip(err));
                }
            }
            catch (Exception ex)
            {
                return Json(ErrorTip(ex.ToString()));
            }
        }
    }
}